import axios from 'axios';
import type { Product, ApiResponse, PaginationParams, PaginationResponse, RealApiResponse, RealPaginationData, RawProductData } from '../types/product';

export const API_BASE_URL = axios.defaults.baseURL || 'http://localhost:5118';

// 为产品API创建一个专用的axios实例
const productApi = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
});

// 为专用实例配置拦截器
productApi.interceptors.response.use(
  (response) => {
    // 这个拦截器只影响使用productApi的请求
    return response.data;
  },
  (error) => {
    console.error('API请求错误:', error);
    return Promise.reject(error);
  }
);

// 数据转换函数：将API返回的商品数据转换为前端格式
const transformProduct = (apiProduct: RawProductData): Product => {
  return {
    ...apiProduct,
    // 映射字段以兼容现有组件
    name: apiProduct.productName || '',
    description: apiProduct.specification || '',
    category: apiProduct.categoryName || '未分类',
    price: apiProduct.price || 0,
    stock: apiProduct.stock || 0,
  };
};

// 获取商品列表
export const getProductList = async (params: PaginationParams): Promise<ApiResponse<PaginationResponse<Product>>> => {
  try {
    const response: RealApiResponse<RealPaginationData<RawProductData>> = await productApi.get('/api/Product/GetProduct', {
      params: {
        PageIndex: params.pageIndex,
        PageSize: params.pageSize,
      },
    });
    
    console.log('API响应:', response); // 调试日志
    
    // 检查API响应格式
    if (response.code === 200 && response.data) {
      const paginationData = response.data;
      const products = paginationData.data.map(transformProduct);
      
      // 直接返回转换后的 products，不再进行多余的映射
      return {
        success: true,
        message: '获取成功',
        data: {
          items: products,
          total: paginationData.totalCount || 0,
          pageIndex: params.pageIndex,
          totalPages: paginationData.totalPage || 0,
          pageSize: params.pageSize,
        },
      };
    } else {
      throw new Error(`API返回错误: ${response.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : '获取商品列表失败',
      data: {
        items: [],
        total: 0,
        pageIndex: params.pageIndex,
        pageSize: params.pageSize,
        totalPages: 0
      }
    };
  }
};

// 根据ID获取商品详情
export const getProductById = async (id: number): Promise<ApiResponse<Product>> => {
  try {
    const response: RealApiResponse<RawProductData> = await productApi.get(`/api/Product/GetProduct/${id}`);
    
    if (response.code === 200 && response.data) {
      return {
        success: true,
        message: '获取成功',
        data: transformProduct(response.data)
      };
    } else {
      throw new Error(`API返回错误: ${response.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取商品详情失败:', error);
    throw error;
  }
};

// 新增产品
export const createProduct = async (product: Partial<Product>): Promise<RealApiResponse<null>> => {
  return productApi.post('/api/Product/CreateProduct', product);
};

// 修改产品
export const updateProduct = async (product: Partial<Product>): Promise<RealApiResponse<null>> => {
  return productApi.post('/api/Product/UpdateProduct', product);
};

// 上传文件
export const uploadFile = async (file: File): Promise<string> => {
  const formData = new FormData();
  formData.append('file', file);

  const response = await productApi.post('/api/Product/UpFile', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    // 告诉axios我们期望一个纯文本响应
    transformResponse: (data) => data,
  });

  if (typeof response === 'string') {
    return response;
  }

  throw new Error('文件上传失败：服务器返回格式无效。');
};

export const deleteProducts = async (ids: number[]): Promise<RealApiResponse<unknown>> => {
  try {
    const response = await productApi.delete<RealApiResponse<unknown>>('/api/Product/DelProduct', {
      data: { ids: ids.join(',') }, // 根据Swagger，将ID数组转换为逗号分隔的字符串
    }) as unknown as RealApiResponse<unknown>; // 双重断言，解决TS类型推断问题
    return response;
  } catch (error) {
    console.error('删除产品时出错:', error);
    // 构造一个与正常返回结构一致的错误响应
    return {
      code: 500,
      message: (error as Error).message || '网络或服务器错误',
      data: null,
    };
  }
}; 